package com.hbean.system.websocket;


import com.hbean.utils.HUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @Description: null
 * @Project: hbean
 * @Author: hjibo
 * @CreateDate: 2018/11/1 15:25
 * @ModificationHistory: （who whatTime doWhat）
 */

@Slf4j
@ServerEndpoint(value = "/websocket/{userId}")
@Component
public class WebSocketServer {

    private Session session;//新建立的会话
    private static Map<String,Session> sessionPool = new HashMap<>();// key：用户id，value：用户对应的session
    private static Map<String,String> sessionIds = new HashMap<>();// key：sessionId，value：用户Id

    private static AtomicInteger onlineNum =  new AtomicInteger(0);

    /**
     * 有新连接建立时执行的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam(value="userId")String userId) {
        this.session = session;
        sessionPool.put(userId, session);
        sessionIds.put(session.getId(), userId);

        Map dataMap = new HashMap();
        dataMap.put("onlineNum",onlineNum.incrementAndGet());
        this.sendMessageToAll(HUtil.mapToJsonStr(dataMap));

    }

    /**
     * 有连接关闭时执行的方法
     */
    @OnClose
    public void onClose() {
        sessionPool.remove(sessionIds.get(session.getId()));
        sessionIds.remove(session.getId());

        Map dataMap = new HashMap();
        dataMap.put("onlineNum",onlineNum.decrementAndGet());
        this.sendMessageToAll(HUtil.mapToJsonStr(dataMap));
    }

    /**
     * 收到客户端消息时执行的方法
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("客户端(sessionId:" + session.getId() + ")发来新消息");
    }

    /**
     * 信息发送
     * @param message
     * @param userId
     */
    public void sendMessage(String message, String userId) {
        Session session = sessionPool.get(userId);
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 信息群发
     * @param message
     */
    public void sendMessageToAll(String message) {
        for (String key : sessionIds.keySet()) {
            sendMessage(message, sessionIds.get(key));
        }
    }

    /**
     * 信息发送给指定的用户
     * @param message
     * @param userIds 用户id
     */
    public void sendMessageToMany(String message,String [] userIds) {
        for (String userId : userIds) {
            sendMessage(message, userId);
        }

    }

    /**
     * 获取在线用户
     * @return
     */
    public String getOnlineUsers() {
        StringBuffer users = new StringBuffer();
        for (String key : sessionIds.keySet()) {
            users.append(sessionIds.get(key) + ",");
        }
        return users.toString();
    }

    /**
     * 获取在线用户数量
     * @return
     */
//    public int getOnlineNum() {
//        return sessionPool.size();
//    }

}
